<template>
  <div class="container">
    <!-- <div class="getInfoBox" v-if="assessInfo.info.infoValue.length>0&&NotAssess">
      <p >请填写信息</p>
      <el-form  ref="getInfoForm" label-width="120px" inline label-position='left'>
        <el-form-item required  :label="Object.keys(item)[0]+':'" v-for="(item, index) in assessInfo.info.infoValue" :key="index">
          <el-input v-model="item[Object.keys(item)[0]]" placeholder="请输入信息"></el-input>
        </el-form-item>
      </el-form>
      <p style="text-align: center;position: absolute;right: 85px;bottom: 0;">
        <el-button type="primary" @click="validInfoForm('getInfoForm')">开始考核</el-button>
      </p>
    </div> -->
    <div v-loading='loading' element-loading-text='正在 保存' class="assessBox" >
      <div style="width: 100%;display: flex;justify-content: end;">
        <span style="margin-right: 5px;">整卷预览</span>
        <el-switch
          v-model="isPreviewAll"
          active-color="#13ce66"
          @change='()=>showPdf=true'
          >
        </el-switch>
      </div>
      <div class="taskBox" v-if="assessInfo&&!isPreviewAll" >
        <!-- <p style="font-weight: 600;font-size: 24px;">{{taskItemInfo.category}}</p> -->
        <div style="margin-left: 15px;margin-top: 10px;">
          <p style="font-weight: 600;font-size: 22px;">{{assessIndex+1+'.'+taskItemInfo.taskName}}</p>
          <div style="display: flex;">
            <el-form label-position="left" style="margin-top: 20px;flex: 1.5;" >
              <div style="flex: 1;margin-bottom: 10px;">
                <p style="font-weight: 600;font-size: 18px;">评分标准</p>
                <div style="color: #8592a6;line-height: 22px;font-size: 14px;margin-top: 5px;">
                  {{taskItemInfo.standard}}
                </div>
              </div>
              <el-form-item label='评分:' required>
                <el-input-number onkeydown="if (event.keyCode===13){return false;}" :disabled='taskItemInfo.isFile==1&&taskItemInfo.isExtend==1' :max="taskItemInfo.score" :min="0" controls-position="right" placeholder='请输入您的自评分数' style="width: 40%;" v-model.number="pushInfo.resultList[assessIndex].score"></el-input-number>
                <span>限额{{taskItemInfo.score}}分</span>
              </el-form-item>
              <el-form-item>

              </el-form-item>
              <el-form-item style="margin-top: 20px;" label="请上传pdf文件" v-show="taskItemInfo.isFile&&taskItemInfo.isExtend==0">
                <el-upload
                  class="upload-demo"
                  drag
                  action="/api/fileUpload"
                  :headers="{'Authorization':header}"+
                  :before-upload="beforeUpload"
                  ref='upload'
                  :on-success='onSuccess'
                  multiple
                  accept='.pdf'
                  :show-file-list='false'
                  >
                  <i class="el-icon-upload"></i>
                  <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                  <div class="el-upload__tip" slot="tip">只能上传<span style="color: #409eff;">pdf</span>格式文件,且不超过50M</div>
                </el-upload>
              </el-form-item>
              <!-- 可选项 -->
              <el-form-item style="margin-top: 20px;" v-if="taskItemInfo.isFile==1&&taskItemInfo.isExtend==1">
                <el-button type="primary" @click="addExtend" icon='el-icon-plus' size="small"></el-button>
                <el-button  @click="handlerRemove" icon='el-icon-minus' size="small"></el-button>
                <el-table
                    ref="multipleTable"
                    :data="resultExtends"
                    tooltip-effect="dark"
                    style="width: 100%"
                    :border='true'
                    @selection-change="handleSelectionChange"
                    >
                    <el-table-column
                          type="selection"
                          width="55">
                        </el-table-column>
                    <el-table-column
                      label="等级"
                      width="120">
                        <template slot-scope="scope">
                          <el-select v-model="scope.row.itemType" placeholder="请选择">
                            <el-option
                              v-for="item in tireOptions"
                              :key="item.value"
                              :label="item.value"
                              :value="item.value">
                            </el-option>
                          </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column
                      label="名称"
                      width="180">
                      <template slot-scope="scope">
                        <el-input size="small" v-model="scope.row.itemName"></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column
                      label="评分"

                      width="150"
                      >
                      <template slot-scope="scope">
                        <el-input-number required onkeydown="if (event.keyCode===13){return false;}" size="small" @change='scoreChange(true,scope.row)'  :max="taskItemInfo.score" :min="0" controls-position="right" placeholder='自评分数' v-model="scope.row.score"></el-input-number>
                      </template>
                    </el-table-column>
                    <el-table-column
                      label="备注"
                      width="180"
                      >
                      <template slot-scope="scope">
                        <el-input size="mini" v-model="scope.row.note"></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column
                      label="操作"
                      width="150"
                      v-if="taskItemInfo.isFile"
                      >
                      <template slot-scope='scope'>
                        <el-upload
                          class="upload-demo"
                          action="/api/fileUpload"
                          :headers="{'Authorization':header}"
                          :before-upload="beforeUpload"
                          :on-success='(response, file, fileList)=>onSuccess(response, file, fileList,scope.row)'
                          multiple
                          accept='.pdf'
                          :show-file-list='false'>
                          <el-button size="small" type="primary">上传佐证材料</el-button>
                        </el-upload>
                        <!-- <el-button size="small" type="danger" @click="removeExtends(scope.$index,scope.row)">移除此列</el-button> -->
                      </template>
                    </el-table-column>
                  </el-table>
              </el-form-item>
            </el-form>

          </div>
          <div style="position: relative;" class="pdfBox scroll" v-if="showPdf&&taskItemInfo.isFile&&pdfList[assessIndex].length>0">
            <el-tabs closable	 @tab-remove='removePdf' v-model="activePdf" type="card" >
                <el-tab-pane :label="'附件'+(index+1)" :name="index.toString()" v-for="(pdfUrl,index) in pdfList[assessIndex]" :key="index">
                  <canvas-preview  :key="index" :index="index" :pdf-url="pdfUrl"></canvas-preview>
                </el-tab-pane>
            </el-tabs>
          </div>
        </div>
      </div>
      <project-template v-else :assessInfo='assessInfo' :flag="'assess'" :showPdf='showPdf' :answerInfoList='pushInfo.resultList' :pdfList='pdfList'>
      </project-template>
      <div style="display: flex;justify-content: flex-end;">
        <div style="margin-top: 30px;"><el-button @click="submitAssess(false)" type="info" size="medium" v-throttle>保存退出</el-button></div>
        <div style="margin-top: 30px;margin-left: 10px;"><el-button @click="nextAssess(false)" size="medium" v-if="!isPreviewAll">上一指标</el-button></div>
        <div style="margin-top: 30px;margin-left: 10px;" v-if="isSubmit&&!isPreviewAll"><el-button @click="nextAssess(true)" size="medium" type="primary">下一指标</el-button></div>
        <div style="margin-top: 30px;margin-left: 10px;" v-else><el-button @click="submitAssess(true)" size="medium" type="primary" v-throttle>提交</el-button></div>
      </div>
    </div>
    <div style="position: absolute;left:110%;top: 0;width: 50%;" v-if="!isPreviewAll">
      <assess-select  @assessChange='assessChange' :assessCategoryInfo='assessCategoryInfo' :assess-count="assessInfo.task.length" :assess-index="assessIndex+1"></assess-select>
    </div>
  </div>
</template>

<script>
  import axios from "axios"
  import canvasPreview from "@/components/canvasPreviewPdf.vue"
  import projectTemplate from "@/components/projectTemplate.vue"
  import assessSelect from "@/components/assessSelect.vue"
  import Cookies from "js-cookie"
  export default{
    name: "assess",
    data(){
      return{
        assessInfo:{
          info:{
            infoValue:[]
          }
        },
        NotAssess:true,
        assessIndex:0,
        pushInfo:{
          // pId: this.$route.query.id,
          //最终上传的内容
          resultList: [],
          // evidenceList: [],
          // evidenceCount: 0,
          // // infoContentList: [],
          // // pdfNames:[],
          // score:0
        },
        header:Cookies.get('token'),
        showPdf:false,
        pdfList:[],
        filelist:[],
        loading:false,
        activePdf:'0',
        isPreviewAll:false,
        // 扩展项等级
        tireOptions:[{value:'国家级'},{value:'省级'},{value:'校级'},{value:'其他'}],
        //扩展项数据
        tableData:[],
        //被选中的扩展项列表
        selTireList:[],
        assessCategoryInfo:[]
      }
    },
    components:{
      canvasPreview,
      projectTemplate,
      assessSelect
    },
    methods:{
      onSuccess(response, file, fileList,row=null){
        // let arr=this.pdfList[this.assessIndex]
        let arr=[...this.pdfList[this.assessIndex],...response.data]
        this.pdfList[this.assessIndex]=arr
        this.showPdf=false
        if(row){
          row.evidenceList.push(...response.data)
        }
        // this.pdfList[this.assessIndex].push(...response.data)
        this.$nextTick(()=>{
          this.showPdf=true
        })
        // console.log(response)
        this.pushInfo.resultList[this.assessIndex].evidenceList.push(...response.data)
      },

      // flag:true 修改扩展项分数
      scoreChange(flag,row){
        if(flag){
          let score=0
          this.resultExtends.map(item=>{
            if(Number.isInteger(item.score)){
              score+=item.score
            }
          })
          if(score>this.taskItemInfo.score) { 
            this.$message.info('扩展项总分不能大于该考核点最高分')
            this.$nextTick(()=>{
              this.pushInfo.resultList[this.assessIndex].score=score-row.score
              row.score=0
              })
          }else{
            console.log(score)
            return this.pushInfo.resultList[this.assessIndex].score=score
          }
        }
        this.pushInfo.resultList[this.assessIndex].scoreChange=true
      },
      assessChange(val){
        this.assessIndex=val
        this.showPdf=false
        this.$nextTick(()=>{
          this.showPdf=true
        })
      },
      async initAssess(){
        let result= await this.$get('/api/result/detail/'+this.$route.query.id)
        // let stagingInfo =await this.$get('/api/project/Staging/'+this.$route.query.id)
        //初始化上传佐证材料对象 需上传文件数量
        // result.data.task.length=3
        let categoryInfoArr=[]
        // 考核点类别
        let categorySet=new Set()
        let categoryArr=[]
        if(result.data.results.length!=0){
          this.pushInfo.pId=result.data.results[0].pid
          //保存过则初始化pdflist时使用结果中的task任务避免出现顺序问题
          let arr=[]
          result.data.results.forEach(item=>{
            arr.push(item)
          })
          arr.forEach((item,index)=>{
            if(item.task.isFile) {
              this.pdfList[index]=[]
            }
            categorySet.add(item.task.category)
          })
          categoryArr=[...categorySet]
          let index=0
          categoryArr.forEach(item=>{
            let list=[]
            let tempCategoryArr=arr.filter(items=>items.task.category==item)
            tempCategoryArr.forEach(items=>{
              list.push({index,item:items})
              index++
            })
            this.assessCategoryInfo.push({title:item,list})
            categoryInfoArr.push(...tempCategoryArr)
          })
        }else{
          this.pushInfo.pId=result.data.task[0].pid
          result.data.task.map((item,index)=>{
            if(item.isFile) {
              this.pdfList[index]=[]
            }
          })
        }
        if(result.data.results.length>0){
          // 保存过
          this.pushInfo.resultList=result.data.results
          this.pushInfo.resultList.map((item,index)=>{
            if(index==0&&item.evidenceList.length!=0)this.showPdf=true
            if(this.pdfList[index]!=undefined) this.pdfList[index]=item.evidenceList
            if(item.task.isFile==1&&item.task.isExtend==1&&item.resultExtends.length==0) {
              // console.log()
              item.resultExtends=[{
                  itemType:'',
                  itemName:'',
                  score:undefined,
                  note:'',
                  evidenceList:[],
                  index:0
                }]
            }else if(item.task.isFile==1&&item.task.isExtend==1&&item.resultExtends.length!=0){
              item.resultExtends.map((item,index)=>{
                item.index=index
              })
            }
          })
        }else{
          //将考核点按照分类添加进此数组
          result.data.task.forEach((item,index)=>{
            let obj={
              pId:item.pid,
              taskId:item.id,
              evidenceList:[],
              evidenceCount:0,
              scoreChange:false,
              resultExtends:undefined
            }
            if(item.isFile==1&&item.isExtend==1){
              console.log(obj,'-----------')
              obj.resultExtends=[{
                itemType:'',
                itemName:'',
                score:undefined,
                note:'',
                evidenceList:[],
                index:0
              }]
            }
            this.$set(obj,'score',undefined)
            categorySet.add(item.category)
            this.pushInfo.resultList.push(obj)
          })
          categoryArr=[...categorySet]
          let index=0
          categoryArr.forEach(item=>{
            let list=[]
            let tempCategoryArr=result.data.task.filter(items=>items.category==item)
            tempCategoryArr.forEach(item=>{
              list.push({index,item:this.pushInfo.resultList[index]})
              index++
            })
            this.assessCategoryInfo.push({title:item,list})
            categoryInfoArr.push(...tempCategoryArr)
          })
        }
        // if(result.data.info.infoValue.length==0) this.NotAssess=false
        this.assessInfo=result.data

      },
       validInfoForm(formName) {
        // let result=this.assessInfo.info.infoValue.every(item=>item[Object.keys(item)[0]].trim()!="")
        // result?this.NotAssess=false:this.$message.warning('请完善信息内容')
      },
      beforeUpload(file){
        let reg=/.*(pdf)$/
        if(!reg.test(file.name)) {
          this.$message.error('请上传pdf格式的文件')
          return false
        }
        if(file.size / 1024 / 1024 > 50){
          this.$message.error('文件不能大于50M')
          return false
        }
      },
      onChange(file,fileList){

      },
      removePdf(index){
        this.$confirm('是否删除该文件?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.showPdf=false
          let arr=this.pdfList[this.assessIndex].splice(index,1)
          this.pushInfo.resultList[this.assessIndex].evidenceList.splice(index,1)
          if(this.resultExtends){
            // this.resultExtends.splice(this.resultExtends.indexOf(arr[0]),1)
            this.resultExtends.map(item=>{
              if(item.evidenceList.indexOf(arr[0])!=-1)item.evidenceList.splice(item.evidenceList.indexOf(arr[0]),1)
            })
          }
          this.$nextTick(()=>{
            this.showPdf=true
          })
          if(this.activePdf===index){
            if(index>1)this.activePdf=(index-1).toString()
            else this.activePdf='0'
          }
        }).catch((e) => {
          console.log(e)
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      nextAssess(flag){
        this.showPdf=false
        this.$nextTick(()=>{
          this.showPdf=true
        })
        flag?this.assessIndex++:this.assessIndex--
        this.activePdf='0'
      },
      // flag为true则提交
      async submitAssess(flag){
        this.$confirm(flag?'确认提交考核结果? 提交后将不能修改！':'是否退出并保存此次考核?', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                }).then(async () => {
                  // this.pushInfo.infoContentList=this.assessInfo.info.infoValue
                  console.log(123)
                  if(flag){
                    let isAllWrite=false
                    let assessIndex=0
                    isAllWrite=this.pushInfo.resultList.every((items,index)=>{
                      if(items.score==undefined){
                        assessIndex=index
                        return false
                      }
                      return true
                    })
                    if(!isAllWrite){
                      assessIndex++
                      return this.$message.warning('您的第'+assessIndex+'题还未填写')
                    }
                    let evidenceFlag= this.pdfList.every((item,index)=>{
                      assessIndex=index
                      if(item!=undefined&&item.length==0&&this.pushInfo.resultList[index].score!=0)return false
                      else if(this.pushInfo.resultList[index].resultExtends.length!=0){
                        let flag=true
                        this.pushInfo.resultList[index].resultExtends.forEach(items=>{
                          if(items.evidenceList.length==0&& Number.isInteger(items.score)&&items.score>0){
                            flag=false
                          }
                        })
                        console.log(flag)
                        return flag
                      }
                      else return true
                    })
                    if(!evidenceFlag){
                       assessIndex++
                      return this.$message.warning('您的第'+assessIndex+'题未上传佐证材料')
                    }
                  }
                  // this.pdfFileUpload(this.pdfList,flag)
                  let str='/api/project/result'
                  let result=await this.$post(str,{projectId:parseInt(this.$route.query.id),results:this.pushInfo.resultList,isFlag:flag?4:5})
                  this.loading=false
                  if(result.code!=200) return this.$message.warning(result.msg)
                  this.$message.success(result.msg)
                  this.$store.commit('removeAnalogueTab',"/home/assess")
                  this.$router.push('/home/project')
                })
      },
      pdfFileUpload(list,flag){
        //单个任务上传文件数量的集合
        let tempArr=[]
        //异步任务集合
        let promiseArr=[]
        //单个任务上传文件的文件集合
        let formDataArr=[]
        this.loading=true
        list.map(item=>{
          let count=0
          item.map(items=>{
            // this.pushInfo.pdfNames.push(items.name)
            let formData=new FormData()
            formData.append('file',items)
            formDataArr.push(formData)
            count++
          })
          tempArr.push(count)
        })
        promiseArr=formDataArr.map(item=>{
          return this.pdfFileUploadHandler(item,flag)
        })
        console.log(tempArr)
        Promise.all(promiseArr).then(async res=>{
          // if(res.length==0){
          //   this.loading=false
          //   return this.$message.error('文件上传失败')
          // }

          console.log(res)
          // let  evidenceList=this.pushInfo.evidenceList
          // this.pushInfo.evidenceList.map((item,index)=>{
          //   for(let i=0; i< tempArr[index];i++){
          //     evidenceList[index][Object.keys(evidenceList[index])[0]].push(...res.shift().data)
          //   }
          // })
          // let str=flag?'/api/project/result':'/api/project/Staging'
          // let result=await this.$post(str,this.pushInfo)
          // this.loading=false
          // if(result.code!=200) return this.$message.warning(result.msg)
          // this.$message.success(result.msg)
          // this.$router.back()
        })
        .catch(rej=>{
          this.loading=false
          this.$message.error('提交失败:'+rej)
        })
      },
      /**
       * @param {blob} data pdf文件
       * @param {boolean} flag true为提交false为暂存
       * */
      pdfFileUploadHandler(data,flag){
        return new Promise((resolve,reject)=>{
                axios({
                url:'/api/fileUpload',
                method:'post',
                headers: {
                  'Content-Type': 'multipart/form-data',
                  'Authorization':this.header
                },
                data,
                params:{flag:flag?1:0}
              }).then(res=>{
                resolve(res)
              })
        })
      },
      handleSelectionChange(val){
        this.selTireList=val
      },
      //添加可选项
      addExtend(){
        let obj={
          itemType:'',
          itemName:'',
          score:undefined,
          note:'',
          evidenceList:[],
          index:this.resultExtends.length
        }
        this.resultExtends.push(obj)
      },
      handlerRemove(){
        this.selTireList.map(item=>{
          this.removeExtends(item.index,item)
        })
      },
      //删除可选项
      removeExtends(index,row){
          if(this.resultExtends.length>1){
            this.showPdf=false
            // 通过index判断删除的是resultExtends中的哪个
            this.resultExtends.map((item,resultExtendsIndex)=>{
              if(item.index==index){
                console.log(index)
                item.evidenceList.map(item=>{
                  let resEvidenceList=this.pushInfo.resultList[this.assessIndex].evidenceList
                  let curPdfList=this.pdfList[this.assessIndex]
                  //删除pushInfo中对应对象的pdf文件
                  resEvidenceList.splice(resEvidenceList.indexOf(item),1)
                  //删除resultExtends对应对象的pdf文件
                  curPdfList.splice(curPdfList.indexOf(item),1)
                })
                this.resultExtends.splice(resultExtendsIndex,1)
              }
            })
            this.$nextTick(()=>{
              this.scoreChange(true,row)
              this.showPdf=true
            })

          }else this.$message.info('至少保留一条扩展项！')
      }
      },
    created(){
      this.$store.commit('removeAnalogueTab',"/home/assess")
      this.$nextTick(()=>{
        this.$store.commit('setTabs',{
          name: "/home/assess?id="+this.$route.query.id,
          title: "项目考核"
        })
      })
      this.initAssess()
    },
    computed:{
      //
      taskItemInfo(){
        return this.assessInfo.results.length>0?this.assessInfo.results[this.assessIndex].task:this.assessInfo.task[this.assessIndex]
      },
      isSubmit(){
        return this.assessIndex<this.assessInfo.task.length-1||false
      },
      answerInfoList(){
        return this.pushInfo.resultList[this.assessIndex]||[]
      },
      resultExtends:{
        get(){
          return this.pushInfo.resultList[this.assessIndex].resultExtends
        },
        set(val){
          this.pushInfo.resultList[this.assessIndex].resultExtends.push(val)
        }
      }
    },
    watch:{
      assessIndex(){
        if(this.assessIndex<0) {
          this.assessIndex=0
          this.NotAssess=true
        }
        this.activePdf='0'
      }
    }
  }
</script>

<style scoped lang="scss">
  .container{
    margin: 20px 30px;
    width: 60%;
    height: 100%;
    position: relative;
    padding-bottom: 20px;
  }
  .getInfoBox{
    width: 100%;
    position: relative;
    min-height: 500px;
    >p{
      font-size: 24px;
      color: #999;
      margin-bottom: 30px;
    }
  }
  .taskBox{
    height: 100%;
    min-height: 500px;
    position: relative;
    >p{
      font-size: 20px;
      font-weight: 500;
    }
  }
  .assessBox{
    min-height: 500px;
    /deep/ .el-form-item{
      margin-bottom: -5px;
    }
  }
  .pdfBox{
    height: 500px;
    overflow: auto;
    margin-top: 30px;
  }
  .scroll {
      overflow: auto;
     }

     .scroll::-webkit-scrollbar {
      width: 4px;
      height: 4px;
     }

     .scroll::-webkit-scrollbar-thumb {
      border-radius: 10px;
      background: #444;
     }

     .scroll::-webkit-scrollbar-track {
      border-radius: 0;
      background-color: rgba(0 ,0 , 0 , .1 );
     }
   /deep/ .el-tabs__header{
     position: sticky;
     background-color: white;
     top: 0;
     z-index: 2;
   }
   /deep/ .el-radio-group{
     display: flex;
     justify-content: start;
     flex-wrap: wrap;
     label{
       margin: 0 10px;
       margin-bottom: 20px;
       .el-radio-button__inner,div{
         width: 60px;
         border-left: 1px solid #DCDFE6;
       }
       .el-radio-button__orig-radio:checked+.el-radio-button__inner{
         border-left: 0;
       }
     }
   }
   /deep/ .cell{
     overflow: initial;
   }
</style>
